using MicroMsg.Common.Utils;
using MicroMsg.Network;
using MicroMsg.Resource.@string;
using MicroMsg.UI.ImageFilter;
using MicroMsg.UI.UserContrl;
using MicroMsg.UI.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
namespace MicroMsg.UI.Page
{
	public class ImageFilterPage : BasePage
	{
		private const string TAG = "ImageFilterPage";
		private Dictionary<string, WriteableBitmap> resultCache = new Dictionary<string, WriteableBitmap>();
		private ImageFilterMgr imageFilterMgr;
		private PhotoChooserTask photoChooserTask_0;
		private CameraCaptureTask photoCameraCapture;
		private WriteableBitmap lastestImage;
		private bool initState;
		public static ImageFilterItem CurrentFilterItem;
		public static FilterSetting CurrentFilterType;
		private ImageFilterConfig config;
		private static int mTotalMemory = 0;
		private ApplicationBar mBar;
		private ApplicationBarIconButton mOkButton;
		private ApplicationBarIconButton mRotateButton;
		private ApplicationBarMenuItem mRawImageMenu;
		private int mTurnAngle;
		private bool okButton_ClickFlag;
		private MMMessageBox m2GWarningDlg;
		internal Grid LayoutRoot;
		internal ScrollViewer scrollViewer;
		internal Image image_0;
		internal Grid listBoxLayout;
		internal ListBox listBox;
		internal PerformanceProgressBar progressBar;
		private bool _contentLoaded;
		public ImageFilterPage()
		{
			ImageFilterPage.CurrentFilterType = null;
			ImageFilterPage.CurrentFilterItem = null;
			this.InitializeComponent();
		}
		protected override void OnPageIn(object[] object_0)
		{
			try
			{
				if (object_0 != null && object_0.Length > 0)
				{
					this.config = (object_0[0] as ImageFilterConfig);
				}
				if (this.config == null)
				{
					MMMessageBox.Show("请传入滤镜配置参数", true, "确定").ReturnEvent = new DlgReturnEvent(this.finishPage);
				}
				else
				{
					if (this.config.GetPicMode == ImageFilterGetPicMode.GetPicMode_Pass_In)
					{
						if (this.config.SourceImage != null)
						{
							this.showSourceImage(new WriteableBitmap(this.config.SourceImage));
						}
					}
					else
					{
						if (this.config.GetPicMode == ImageFilterGetPicMode.GetPicMode_Take_Photo)
						{
							this.photoCameraCapture = new CameraCaptureTask();
							if (this.photoCameraCapture != null)
							{
								this.photoCameraCapture.add_Completed(new EventHandler<PhotoResult>(this.takePhoto_Completed));
								this.photoCameraCapture.Show();
							}
						}
						else
						{
							if (this.config.GetPicMode == ImageFilterGetPicMode.GetPicMode_Choose_Exist || this.config.GetPicMode == ImageFilterGetPicMode.GetPicMode_Choose_With_Take)
							{
								this.photoChooserTask_0 = new PhotoChooserTask();
								if (this.photoChooserTask_0 != null)
								{
									this.photoChooserTask_0.add_Completed(new EventHandler<PhotoResult>(this.pc_Completed));
									if (this.config.CutWidth > 0 && this.config.CutHeight > 0)
									{
										this.photoChooserTask_0.set_PixelWidth(this.config.CutWidth);
										this.photoChooserTask_0.set_PixelHeight(this.config.CutHeight);
									}
									this.photoChooserTask_0.set_ShowCamera(this.config.GetPicMode == ImageFilterGetPicMode.GetPicMode_Choose_With_Take);
									this.photoChooserTask_0.Show();
								}
							}
						}
					}
				}
			}
			catch (Exception)
			{
				base.GoBack();
			}
		}
		private void filter_ItemClick(object sender, object object_0)
		{
			if (this.progressBar.get_Visibility() == null)
			{
				return;
			}
			FilterSetting filterSetting = object_0 as FilterSetting;
			if (filterSetting != null)
			{
				ImageFilterItem currentFilterItem = ImageFilterPage.CurrentFilterItem;
				FilterSetting currentFilterType = ImageFilterPage.CurrentFilterType;
				ImageFilterPage.CurrentFilterType = filterSetting;
				if (currentFilterItem != null && currentFilterType != null)
				{
					currentFilterItem.RefreshItem(currentFilterType);
				}
				ImageFilterPage.CurrentFilterItem = (sender as ImageFilterItem);
				if (ImageFilterPage.CurrentFilterItem != null)
				{
					ImageFilterPage.CurrentFilterItem.RefreshItem(filterSetting);
				}
				this.doProcessImg(filterSetting.string_0);
			}
		}
		private void pc_Completed(object sender, PhotoResult photoResult_0)
		{
			if (photoResult_0.get_Error() != null)
			{
				MMMessageBox.Show(strings.Set_Personal_CanNotLoadImages, true, "确定").ReturnEvent = new DlgReturnEvent(this.finishPage);
				return;
			}
			if (photoResult_0.get_TaskResult() == 1)
			{
				if (this.checkImageFormat(photoResult_0.get_ChosenPhoto()))
				{
					BitmapImage bitmapImage = new BitmapImage();
					bitmapImage.SetSource(photoResult_0.get_ChosenPhoto());
					this.showSourceImage(new WriteableBitmap(bitmapImage));
				}
				else
				{
					Log.smethod_1("ImageFilterPage", "send gif image is not supported");
					MMMessageBox.Show(strings.ChatImgSendFormatError, true, "确定").ReturnEvent = new DlgReturnEvent(this.finishPage);
				}
			}
			else
			{
				base.get_Dispatcher().BeginInvoke(delegate
				{
					base.GoBack();
				});
			}
			this.photoChooserTask_0 = null;
		}
		private void finishPage(DlgReturnEventArg dlgReturnEventArg_0)
		{
			base.GoBack();
		}
		private bool checkImageFormat(Stream imgStream)
		{
			if (imgStream == null)
			{
				return false;
			}
			imgStream.set_Position(0L);
			byte[] array = new byte[100];
			imgStream.Read(array, 0, 100);
			ImageFromat imageFormat = ImageUtil.getImageFormat(array);
			imgStream.set_Position(0L);
			Log.smethod_5("ImageFilterPage", "image format = " + imageFormat.ToString());
			return imageFormat == ImageFromat.jpeg || imageFormat == ImageFromat.const_2;
		}
		private int getDeviceTotalMemory()
		{
			if (ImageFilterPage.mTotalMemory <= 0)
			{
				object obj = 0;
				DeviceExtendedProperties.TryGetValue("DeviceTotalMemory", ref obj);
				ImageFilterPage.mTotalMemory = (int)((long)obj / 1024L / 1024L);
			}
			return ImageFilterPage.mTotalMemory;
		}
		private void takePhoto_Completed(object sender, PhotoResult photoResult_0)
		{
			if (photoResult_0.get_Error() != null)
			{
				MMMessageBox.Show(strings.Set_Personal_CanNotTakePhoto, true, "确定").ReturnEvent = new DlgReturnEvent(this.finishPage);
				return;
			}
			try
			{
				if (photoResult_0.get_TaskResult() == 1)
				{
					int ibyte = 0;
					for (int i = 0; i < 3; i++)
					{
						photoResult_0.get_ChosenPhoto().Seek((long)(54 + i), 0);
						ibyte = photoResult_0.get_ChosenPhoto().ReadByte();
						if (ibyte != 0)
						{
							break;
						}
					}
					Stream stream = photoResult_0.get_ChosenPhoto();
					if (this.getDeviceTotalMemory() <= 256)
					{
						stream = new MemoryStream();
						Util.saveThumb(photoResult_0.get_ChosenPhoto(), stream, 640, 480, 100);
						photoResult_0.get_ChosenPhoto().Close();
					}
					this.LayoutRoot.set_Visibility(0);
					this.progressBar.set_Visibility(0);
					this.initFilterListBox();
					base.get_Dispatcher().BeginInvoke(delegate
					{
						int num = Math.Abs(90 * (ibyte - 1)) % 360;
						if (num != 0)
						{
							BitmapImage bitmapImage = new BitmapImage();
							bitmapImage.SetSource(stream);
							WriteableBitmap image = new WriteableBitmap(bitmapImage);
							this.showSourceImage(ImageFilterPage.rotatePicture(image, num));
						}
						else
						{
							BitmapImage bitmapImage2 = new BitmapImage();
							bitmapImage2.SetSource(stream);
							WriteableBitmap srcIamge = new WriteableBitmap(bitmapImage2);
							this.showSourceImage(srcIamge);
						}
						this.progressBar.set_Visibility(1);
					});
				}
				else
				{
					base.get_Dispatcher().BeginInvoke(delegate
					{
						base.GoBack();
					});
				}
			}
			catch (Exception ex)
			{
				Log.smethod_1("ImageFilterPage", ex.get_Message() + "\n stackTrace:\n" + ex.get_StackTrace());
				base.get_Dispatcher().BeginInvoke(delegate
				{
					base.GoBack();
				});
			}
			this.photoCameraCapture = null;
		}
		private static WriteableBitmap rotatePicture(WriteableBitmap image, int angle)
		{
			WriteableBitmap writeableBitmap = null;
			if (angle == 90)
			{
				writeableBitmap = new WriteableBitmap(image.get_PixelHeight(), image.get_PixelWidth());
				for (int i = 0; i < image.get_PixelHeight(); i++)
				{
					for (int j = 0; j < image.get_PixelWidth(); j++)
					{
						writeableBitmap.get_Pixels()[writeableBitmap.get_PixelWidth() * j + (writeableBitmap.get_PixelWidth() - 1 - i)] = image.get_Pixels()[image.get_PixelWidth() * i + j];
					}
				}
			}
			else
			{
				if (angle == 180)
				{
					writeableBitmap = new WriteableBitmap(image.get_PixelWidth(), image.get_PixelHeight());
					for (int k = 0; k < image.get_PixelHeight(); k++)
					{
						for (int l = 0; l < image.get_PixelWidth(); l++)
						{
							writeableBitmap.get_Pixels()[writeableBitmap.get_PixelWidth() * (writeableBitmap.get_PixelHeight() - 1 - k) + (writeableBitmap.get_PixelWidth() - 1 - l)] = image.get_Pixels()[image.get_PixelWidth() * k + l];
						}
					}
				}
				else
				{
					if (angle == 270)
					{
						writeableBitmap = new WriteableBitmap(image.get_PixelHeight(), image.get_PixelWidth());
						for (int m = 0; m < image.get_PixelHeight(); m++)
						{
							for (int n = 0; n < image.get_PixelWidth(); n++)
							{
								writeableBitmap.get_Pixels()[writeableBitmap.get_PixelWidth() * (writeableBitmap.get_PixelHeight() - 1 - n) + m] = image.get_Pixels()[image.get_PixelWidth() * m + n];
							}
						}
					}
				}
			}
			return writeableBitmap;
		}
		private void showSourceImage(WriteableBitmap srcIamge)
		{
			if (srcIamge == null)
			{
				base.get_Dispatcher().BeginInvoke(delegate
				{
					base.GoBack();
				});
			}
			this.resultCache.set_Item("Normal", srcIamge);
			this.image_0.set_Source(srcIamge);
			if (this.config.isNeedFilter)
			{
				this.imageFilterMgr = new ImageFilterMgr(srcIamge);
				base.get_Dispatcher().BeginInvoke(delegate
				{
					this.imageFilterMgr.ReadSrcImg();
				});
			}
			this.lastestImage = srcIamge;
			this.LayoutRoot.set_Visibility(0);
			this.initFilterListBox();
			base.set_ApplicationBar(this.GetApplicationBar());
		}
		private void initFilterListBox()
		{
			if (!this.initState && this.config.isNeedFilter)
			{
				Dictionary<string, FilterSetting> filterSettingMap = ImageFilterMgr.GetFilterSettingMap();
				this.listBox.set_ItemsSource(filterSettingMap.get_Values());
				this.initState = true;
				this.listBoxLayout.set_Visibility(0);
				this.scrollViewer.set_Margin(new Thickness(0.0, 30.0, 0.0, 0.0));
			}
		}
		public void doProcessImg(string filterType)
		{
			if (this.resultCache.ContainsKey(filterType))
			{
				this.image_0.set_Source(this.resultCache.get_Item(filterType));
				this.lastestImage = this.resultCache.get_Item(filterType);
				return;
			}
			this.progressBar.set_Visibility(0);
			this.mOkButton.set_IsEnabled(false);
			base.get_Dispatcher().BeginInvoke(delegate
			{
				WriteableBitmap writeableBitmap = this.imageFilterMgr.ProcessImg(filterType);
				this.image_0.set_Source(writeableBitmap);
				this.resultCache.set_Item(filterType, writeableBitmap);
				this.lastestImage = writeableBitmap;
				this.progressBar.set_Visibility(1);
				this.mOkButton.set_IsEnabled(true);
			});
		}
		private static Stream bitmapToStream(BitmapSource image)
		{
			MemoryStream memoryStream = new MemoryStream();
			WriteableBitmap writeableBitmap = new WriteableBitmap(image);
			Extensions.SaveJpeg(writeableBitmap, memoryStream, image.get_PixelWidth(), image.get_PixelHeight(), 0, 100);
			memoryStream.Seek(0L, 0);
			return memoryStream;
		}
		public IApplicationBar GetApplicationBar()
		{
			if (this.mBar != null)
			{
				return this.mBar;
			}
			this.mBar = new ApplicationBar();
			this.mBar.set_IsMenuEnabled(true);
			this.mBar.set_IsVisible(true);
			this.mRotateButton = new ApplicationBarIconButton(new Uri("/Resource/Img/CommonUse/icon_rotate.png", 2));
			this.mRotateButton.set_Text(strings.Filter_Rotate_Image);
			this.mRotateButton.add_Click(new EventHandler(this.rotateButton_Click));
			this.mBar.get_Buttons().Add(this.mRotateButton);
			this.mOkButton = new ApplicationBarIconButton(new Uri("/Resource/Img/CommonUse/ico_save.png", 2));
			this.mOkButton.set_Text(strings.COM_Confirm);
			this.mOkButton.add_Click(new EventHandler(this.okButton_Click));
			this.mBar.get_Buttons().Add(this.mOkButton);
			if (this.config.RawImageHandleCallBack != null)
			{
				this.mRawImageMenu = new ApplicationBarMenuItem(strings.Image_HDImageNoCompress);
				this.mRawImageMenu.add_Click(new EventHandler(this.mRawImageMenu_Click));
				this.mBar.get_MenuItems().Add(this.mRawImageMenu);
			}
			return this.mBar;
		}
		private void rotateButton_Click(object sender, EventArgs e)
		{
			this.mTurnAngle += 90;
			Duration duration = new Duration(TimeSpan.FromMilliseconds(500.0));
			Storyboard storyboard = new Storyboard();
			storyboard.set_Duration(duration);
			DoubleAnimation doubleAnimation = new DoubleAnimation();
			doubleAnimation.set_Duration(duration);
			storyboard.get_Children().Add(doubleAnimation);
			RotateTransform rotateTransform = new RotateTransform();
			Storyboard.SetTarget(doubleAnimation, rotateTransform);
			Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("Angle", new object[0]));
			doubleAnimation.set_To(new double?((double)this.mTurnAngle));
			doubleAnimation.set_From(new double?((double)(this.mTurnAngle - 90)));
			this.image_0.set_RenderTransform(rotateTransform);
			this.image_0.set_RenderTransformOrigin(new Point(0.5, 0.5));
			storyboard.Begin();
		}
		private void okButton_Click(object sender, EventArgs e)
		{
			if (this.lastestImage != null)
			{
				if (this.okButton_ClickFlag)
				{
					return;
				}
				this.okButton_ClickFlag = true;
				base.get_ApplicationBar().set_IsVisible(false);
				this.progressBar.set_Visibility(0);
				base.get_Dispatcher().BeginInvoke(delegate
				{
					this.mTurnAngle %= 360;
					if (this.mTurnAngle != 0)
					{
						this.lastestImage = ImageFilterPage.rotatePicture(this.lastestImage, this.mTurnAngle);
					}
					Stream imageStream = ImageFilterPage.bitmapToStream(this.lastestImage);
					if (this.config.isSaveToAlbum)
					{
						try
						{
							MediaLibrary mediaLibrary = new MediaLibrary();
							mediaLibrary.SavePicture(this.GetExisPicName(), imageStream);
							imageStream.Seek(0L, 0);
						}
						catch (Exception ex)
						{
							Log.smethod_1(base.GetType().get_Name(), "SavaPic Exception" + ex.get_StackTrace());
							MMMessageBox.Show(strings.ImageViewSaveFail, true, "确定");
						}
					}
					if (this.config.ForwardPageUri != null && this.config.ForwardPageUri.get_Length() > 0)
					{
						base.GoToPage(this.config.ForwardPageUri, new object[]
						{
							imageStream
						}, true);
						return;
					}
					if (this.config.ImageFilterCallBack != null)
					{
						base.GoBack();
						base.get_Dispatcher().BeginInvoke(delegate
						{
							this.config.ImageFilterCallBack(imageStream);
						});
					}
				});
			}
		}
		private void mRawImageMenu_Click(object sender, EventArgs e)
		{
			if (this.lastestImage != null && !this.okButton_ClickFlag)
			{
				if (NetworkDeviceWatcher.isCurrentCell3G() || NetworkDeviceWatcher.isCurrentCell2G())
				{
					string text = ((double)ImageFilterPage.bitmapToStream(this.lastestImage).get_Length() * 1.0 / 1024.0).ToString();
					int num = text.IndexOf(".");
					if (num > 0)
					{
						text = text.Substring(0, num + 2);
					}
					text += "KB ";
					string string_ = string.Format(strings.Image_Send_Warning, text);
					this.m2GWarningDlg = MMMessageBox.Show("", string_, true, strings.COM_Send, strings.COM_Cancel);
					this.m2GWarningDlg.ReturnEvent = new DlgReturnEvent(this.warningDlgReturn);
					return;
				}
				this.processAndSend();
			}
		}
		public void warningDlgReturn(DlgReturnEventArg dlgReturnEventArg_0)
		{
			this.m2GWarningDlg = null;
			switch (MMMessageBox.GetUserClickResult(dlgReturnEventArg_0))
			{
			case -1:
				base.GoBack();
				return;
			case 0:
				this.processAndSend();
				return;
			case 1:
				base.GoBack();
				return;
			default:
				return;
			}
		}
		public void processAndSend()
		{
			this.okButton_ClickFlag = true;
			base.get_ApplicationBar().set_IsVisible(false);
			this.progressBar.set_Visibility(0);
			base.get_Dispatcher().BeginInvoke(delegate
			{
				this.mTurnAngle %= 360;
				if (this.mTurnAngle != 0)
				{
					this.lastestImage = ImageFilterPage.rotatePicture(this.lastestImage, this.mTurnAngle);
				}
				Stream imageStream = ImageFilterPage.bitmapToStream(this.lastestImage);
				if (this.config.isSaveToAlbum)
				{
					try
					{
						MediaLibrary mediaLibrary = new MediaLibrary();
						mediaLibrary.SavePicture(this.GetExisPicName(), imageStream);
						imageStream.Seek(0L, 0);
					}
					catch (Exception ex)
					{
						Log.smethod_1(base.GetType().get_Name(), "SavaPic Exception" + ex.get_StackTrace());
						MMMessageBox.Show(strings.ImageViewSaveFail, true, "确定");
					}
				}
				if (this.config.ForwardPageUri != null && this.config.ForwardPageUri.get_Length() > 0)
				{
					base.GoToPage(this.config.ForwardPageUri, new object[]
					{
						imageStream
					}, true);
					return;
				}
				if (this.config.RawImageHandleCallBack != null)
				{
					base.GoBack();
					base.get_Dispatcher().BeginInvoke(delegate
					{
						this.config.RawImageHandleCallBack(imageStream);
					});
				}
			});
		}
		private string GetExisPicName()
		{
			return "Image" + DateTime.get_Now().get_Ticks() + ".jpg";
		}
		protected override void OnBackKeyPress(CancelEventArgs cancelEventArgs_0)
		{
			if (this.okButton_ClickFlag)
			{
				cancelEventArgs_0.set_Cancel(true);
			}
			base.OnBackKeyPress(cancelEventArgs_0);
		}
		[DebuggerNonUserCode]
		public void InitializeComponent()
		{
			if (this._contentLoaded)
			{
				return;
			}
			this._contentLoaded = true;
			Application.LoadComponent(this, new Uri("/MicroMsg;component/Source/UI/ImageFilter/ImageFilterPage.xaml", 2));
			this.LayoutRoot = (Grid)base.FindName("LayoutRoot");
			this.scrollViewer = (ScrollViewer)base.FindName("scrollViewer");
			this.image_0 = (Image)base.FindName("img");
			this.listBoxLayout = (Grid)base.FindName("listBoxLayout");
			this.listBox = (ListBox)base.FindName("listBox");
			this.progressBar = (PerformanceProgressBar)base.FindName("progressBar");
		}
	}
}
